@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>供应商退货表单</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #f8f9fa;
            font-family: 'Microsoft YaHei', sans-serif;
            font-size: 14px;
        }
        .form-container {
            padding: 24px;
            background: #fff;
            margin: 16px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .form-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid #e8e8e8;
        }
        .form-title {
            font-size: 18px;
            font-weight: 500;
            color: #262626;
        }
        .close-btn {
            width: 28px;
            height: 28px;
            line-height: 26px;
            text-align: center;
            background: #f5f5f5;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            color: #666;
            font-size: 16px;
        }
        .close-btn:hover {
            background: #e6f7ff;
            border-color: #40a9ff;
        }
        .layui-form-item {
            margin-bottom: 20px;
        }
        .layui-form-label {
            width: 120px;
            padding: 9px 15px 9px 0;
            text-align: right;
            font-size: 14px;
            color: #262626;
        }
        .layui-input-block {
            margin-left: 130px;
        }
        .required {
            color: #ff4d4f;
            margin-right: 4px;
        }
        .form-buttons {
            text-align: center;
            padding: 24px 0 0 0;
            border-top: 1px solid #e8e8e8;
            margin-top: 24px;
        }
        .layui-btn {
            padding: 0 32px;
            height: 40px;
            line-height: 40px;
            border-radius: 6px;
            font-size: 14px;
        }
        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin: 0 -12px;
        }
        .form-col {
            flex: 1;
            padding: 0 12px;
            min-width: 360px;
        }
        .form-col-full {
            flex: 1;
            padding: 0 12px;
            width: 100%;
        }
        .auto-generate-container {
            position: relative;
        }
        .auto-generate-switch {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
        }
        .layui-input[readonly] {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
        .supplier-select {
            position: relative;
        }
        .supplier-search-btn {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            width: 24px;
            height: 24px;
            border: none;
            background: #f0f0f0;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }
        .supplier-search-btn:hover {
            background: #e6f7ff;
            color: #1890ff;
        }
        .layui-textarea {
            min-height: 100px;
            resize: vertical;
        }
        .layui-form-select .layui-input {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-header">
            <div class="form-title">添加供应商退货</div>
            <div class="close-btn" id="closeBtn">×</div>
        </div>
        
        <form class="layui-form" id="supplierReturnsForm" lay-filter="supplierReturnsForm">
            <input type="hidden" name="id" id="recordId">
            <input type="hidden" name="concurrencyStamp" id="concurrencyStamp">
            <input type="hidden" id="selectedSupplierCode">
            <input type="hidden" name="materielCode" id="selectedMaterielCodes">
            
            <div class="form-row">
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span>退货单编号</label>
                        <div class="layui-input-block auto-generate-container">
                            <input type="text" name="returnCode" lay-verify="required" placeholder="请输入退货单编号" class="layui-input" id="returnCodeInput">
                            <div class="auto-generate-switch">
                                <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动生成|手动输入" checked>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span>退货单名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="returnName" lay-verify="required" placeholder="请输入退货单名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label">采购订单编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="procurementCode" placeholder="请输入采购订单编号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span>供应商</label>
                        <div class="layui-input-block supplier-select">
                            <input type="text" name="vendor" lay-verify="required" placeholder="请选择供应商" class="layui-input" readonly>
                            <button type="button" class="supplier-search-btn" id="supplierSearchBtn">
                                <i class="layui-icon layui-icon-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label">批次号</label>
                        <div class="layui-input-block">
                            <input type="text" name="lotNumber" placeholder="请输入批次号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span>退货日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="returnDate" lay-verify="required" placeholder="请选择退货日期" class="layui-input" id="returnDate">
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <div class="form-col">
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-block">
                            <select name="documentStatus">
                                <option value="">草稿</option>
                                <option value="0">草稿</option>
                                <option value="1">待审核</option>
                                <option value="2">已审核</option>
                                <option value="3">已完成</option>
                                <option value="4">已取消</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-col">
                    <!-- 预留位置 -->
                </div>
            </div>

            <div class="form-row">
                <div class="form-col-full">
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="remark" placeholder="请输入内容" class="layui-textarea"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 物料信息模块 -->
        <div class="material-section" style="margin-top: 24px; padding: 24px; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid #e8e8e8;">
                <h3 style="margin: 0; font-size: 16px; font-weight: 500; color: #262626;">物料信息</h3>
                <div>
                    <button type="button" class="layui-btn layui-btn-sm" id="addMaterialBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 新增
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteMaterialBtn">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button>
                </div>
            </div>
            
            <!-- 搜索区域 -->
            <div style="margin-bottom: 16px;">
                <form class="layui-form" style="display: flex; align-items: center; gap: 12px;">
                    <div style="flex: 1;">
                        <input type="text" name="materialKeyword" placeholder="物料编码/物料名称/规格型号" class="layui-input" style="height: 32px;">
                    </div>
                    <button type="button" class="layui-btn layui-btn-sm" id="searchMaterialBtn">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="resetMaterialBtn">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </form>
            </div>
            
            <!-- 物料产品表格 -->
            <table class="layui-hide" id="materialProductTable" lay-filter="materialProductTable"></table>
        </div>
            
                 <div class="form-buttons" style="margin-top: 24px;">
             <button class="layui-btn" lay-submit lay-filter="saveBtn" form="supplierReturnsForm">保存</button>
             <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
         </div>
     </div>
    </div>

    <script>
        layui.use(['form', 'laydate', 'layer', 'table'], function() {
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var table = layui.table;
            
            // 获取URL参数
            var urlParams = new URLSearchParams(window.location.search);
            var action = urlParams.get('action');
            var id = urlParams.get('id');
            
            console.log('表单参数:', { action, id });
            
            // 如果有ID参数，设置到隐藏字段并加载数据
            if (id) {
                $('#recordId').val(id);
                loadData(id);
            }
            
            // 如果是编辑模式，更新标题
            if (action === 'edit') {
                document.querySelector('.form-title').textContent = '编辑供应商退货';
            } else {
                document.querySelector('.form-title').textContent = '添加供应商退货';
                generateReturnCode(); // 新增时自动生成编号
            }
            
            // 日期选择器
            laydate.render({
                elem: '#returnDate',
                type: 'date',
                format: 'yyyy-MM-dd',
                value: new Date() // 默认今天
            });
            
            // 自动生成开关
            form.on('switch(autoGenerate)', function(data) {
                var checked = data.elem.checked;
                var input = $('#returnCodeInput');
                
                if (checked) {
                    input.attr('readonly', true);
                    generateReturnCode();
                } else {
                    input.attr('readonly', false);
                }
            });
            
            // 生成退货单编号
            function generateReturnCode() {
                var date = new Date();
                var dateStr = date.getFullYear().toString() +
                             (date.getMonth() + 1).toString().padStart(2, '0') +
                             date.getDate().toString().padStart(2, '0');
                var timeStr = date.getHours().toString().padStart(2, '0') +
                             date.getMinutes().toString().padStart(2, '0') +
                             date.getSeconds().toString().padStart(2, '0');
                var code = 'TH' + dateStr + timeStr;
                $('#returnCodeInput').val(code);
            }
            
            // 供应商选择
            $('#supplierSearchBtn').click(function() {
                layer.open({
                    type: 2,
                    title: '选择供应商',
                    area: ['90%', '80%'],
                    maxmin: true,
                    content: '/SupplierReturns/SupplierSelect',
                    success: function(layero, index) {
                        // 设置回调函数
                        window.onSupplierSelected = function(supplier) {
                            console.log('选中的供应商:', supplier);
                            // 显示供应商名称
                            $('input[name="vendor"]').val(supplier.supplierName);
                            // 保存供应商编码到隐藏字段
                            $('#selectedSupplierCode').val(supplier.supplierCode);
                            // 关闭弹窗
                            layer.close(index);
                        };
                    }
                });
            });
            
            // 加载数据
            function loadData(id) {
                $.get('/SupplierReturns/GetById', { id: id })
                    .done(function(result) {
                        if (result.success && result.data) {
                            var data = result.data;
                            
                            // 填充表单数据
                            $('input[name="returnCode"]').val(data.returnCode);
                            $('input[name="returnName"]').val(data.returnName);
                            $('input[name="procurementCode"]').val(data.procurementCode);
                            
                            // 对于编辑模式，vendor字段存储的是SupplierCode，需要查询供应商名称显示
                            $('#selectedSupplierCode').val(data.vendor); // 保存原有的供应商编码
                            
                            // 通过供应商编码查询供应商名称
                            if (data.vendor) {
                                $.get('/SupplierReturns/GetSupplierByCode', { supplierCode: data.vendor })
                                    .done(function(supplierResult) {
                                        if (supplierResult.success && supplierResult.data) {
                                            $('input[name="vendor"]').val(supplierResult.data.supplierName);
                                        } else {
                                            // 如果查询不到供应商，显示编码
                                            $('input[name="vendor"]').val(data.vendor);
                                        }
                                    })
                                    .fail(function() {
                                        // 查询失败时显示编码
                                        $('input[name="vendor"]').val(data.vendor);
                                    });
                            }
                            
                            $('input[name="lotNumber"]').val(data.lotNumber);
                            $('input[name="returnDate"]').val(data.returnDateString);
                            $('select[name="documentStatus"]').val(data.documentStatus);
                            
                            // 设置物料编码
                            if (data.materielCode) {
                                $('#selectedMaterielCodes').val(data.materielCode);
                                console.log('加载的物料编码:', data.materielCode);
                            }
                            
                            // 设置并发标记
                            if (data.concurrencyStamp) {
                                $('#concurrencyStamp').val(data.concurrencyStamp);
                                console.log('加载的并发标记:', data.concurrencyStamp);
                            }
                            
                            // 编辑模式下禁止修改退货单编号
                            $('input[name="autoGenerate"]').prop('checked', false);
                            $('#returnCodeInput').attr('readonly', true);
                            $('.auto-generate-switch').hide();
                            
                            // 重新渲染表单
                            form.render();
                            
                            // 设置物料选中状态（延迟执行，确保表格已渲染）
                            setTimeout(function() {
                                setSelectedMaterials();
                            }, 500);
                        } else {
                            layer.msg(result.message || '加载数据失败', {icon: 2});
                        }
                    })
                    .fail(function() {
                        layer.msg('网络错误，请稍后重试', {icon: 2});
                    });
            }
            
            // 表单提交
            form.on('submit(saveBtn)', function(data) {
                var formData = data.field;
                
                // 移除备注字段（因为数据库中没有这个字段）
                delete formData.remark;
                delete formData.autoGenerate;
                
                // 确保收集最新的物料编码
                collectSelectedMaterials();
                
                // 手动获取字段值（特别是只读字段和隐藏字段）
                var recordId = $('#recordId').val();
                var concurrencyStamp = $('#concurrencyStamp').val();
                var returnCode = $('#returnCodeInput').val() || formData.returnCode;
                var returnName = $('input[name="returnName"]').val() || formData.returnName;
                var procurementCode = $('input[name="procurementCode"]').val() || formData.procurementCode;
                var vendor = $('input[name="vendor"]').val() || formData.vendor;
                var lotNumber = $('input[name="lotNumber"]').val() || formData.lotNumber;
                var returnDate = $('input[name="returnDate"]').val() || formData.returnDate;
                
                // 更新formData
                if (recordId) formData.id = recordId;
                if (concurrencyStamp) formData.concurrencyStamp = concurrencyStamp;
                if (returnCode) formData.returnCode = returnCode;
                if (returnName) formData.returnName = returnName;
                if (procurementCode) formData.procurementCode = procurementCode;
                if (vendor) formData.vendor = vendor;
                if (lotNumber) formData.lotNumber = lotNumber;
                if (returnDate) formData.returnDate = returnDate;
                
                console.log('表单数据验证前:', formData);
                console.log('DOM字段值:', {
                    id: $('#recordId').val(),
                    concurrencyStamp: $('#concurrencyStamp').val(),
                    returnCode: $('#returnCodeInput').val(),
                    returnName: $('input[name="returnName"]').val(),
                    procurementCode: $('input[name="procurementCode"]').val(),
                    vendor: $('input[name="vendor"]').val(),
                    lotNumber: $('input[name="lotNumber"]').val(),
                    returnDate: $('input[name="returnDate"]').val(),
                    action: action
                });
                
                // 数据验证
                if (!formData.returnCode || formData.returnCode.trim() === '') {
                    layer.msg('请输入退货单编号', {icon: 2});
                    return false;
                }
                if (!formData.returnName || formData.returnName.trim() === '') {
                    layer.msg('请输入退货单名称', {icon: 2});
                    return false;
                }
                if (!formData.vendor || formData.vendor.trim() === '') {
                    layer.msg('请选择供应商', {icon: 2});
                    return false;
                }
                if (!formData.returnDate || formData.returnDate.trim() === '') {
                    layer.msg('请选择退货日期', {icon: 2});
                    return false;
                }
                
                // 使用SupplierCode而不是供应商名称
                var supplierCode = $('#selectedSupplierCode').val();
                // 新增时，如果没有选择供应商编码但有供应商名称，也认为是有效的
                if (action !== 'edit' && !supplierCode && !formData.vendor) {
                    layer.msg('请选择供应商', {icon: 2});
                    return false;
                }
                
                // 如果有选择的供应商编码，使用编码；否则使用原有的vendor值（用于编辑时）
                if (supplierCode) {
                    formData.vendor = supplierCode;
                }
                
                // 设置默认值
                if (!formData.procurementCode || formData.procurementCode.trim() === '') {
                    formData.procurementCode = 'N/A'; // 给一个默认值
                }
                if (!formData.lotNumber || formData.lotNumber.trim() === '') {
                    formData.lotNumber = 'N/A'; // 给一个默认值
                }
                if (!formData.documentStatus && formData.documentStatus !== 0) formData.documentStatus = 0;
                
                console.log('最终提交数据:', formData);
                console.log('提交URL:', action === 'edit' ? '/SupplierReturns/Update' : '/SupplierReturns/Create');
                
                // 提交到服务器
                var url = action === 'edit' ? '/SupplierReturns/Update' : '/SupplierReturns/Create';
                
                // 显示加载提示
                var loadIndex = layer.load(1, {shade: [0.1,'#000']});
                
                $.post(url, formData)
                    .done(function(result) {
                        layer.close(loadIndex);
                        console.log('服务器响应:', result);
                        if (result.success) {
                            layer.msg(action === 'edit' ? '修改成功' : '新增成功', {icon: 1}, function() {
                                // 关闭当前窗口
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            });
                        } else {
                            console.error('操作失败:', result);
                            layer.msg(result.message || '操作失败', {icon: 2});
                        }
                    })
                    .fail(function(xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('请求失败:', xhr.responseText);
                        console.error('状态码:', xhr.status);
                        console.error('错误信息:', error);
                        
                        var errorMsg = '网络错误，请稍后重试';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        } else if (xhr.responseText) {
                            try {
                                var errorObj = JSON.parse(xhr.responseText);
                                if (errorObj.message) {
                                    errorMsg = errorObj.message;
                                }
                            } catch (e) {
                                // 解析失败，使用默认错误信息
                            }
                        }
                        
                        layer.msg(errorMsg, {icon: 2});
                    });
                
                return false;
            });
            
            // 取消按钮和关闭按钮
            $('#cancelBtn, #closeBtn').click(function() {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            });
            
            // 初始化时设置自动生成状态
            if (action !== 'edit') {
                $('#returnCodeInput').attr('readonly', true);
            } else {
                // 编辑模式下禁止修改退货单编号
                $('#returnCodeInput').attr('readonly', true);
                // 隐藏自动生成开关
                $('.auto-generate-switch').hide();
            }

            // 初始化物料产品表格
            var materialTableIns = table.render({
                elem: '#materialProductTable',
                url: '/SupplierReturns/GetMaterialProducts',
                method: 'POST',
                page: true,
                limit: 10,
                limits: [10, 20, 50],
                height: 400,
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'materielCode', title: '物料编码', width: 120 },
                    { field: 'materielName', title: '物料名称', width: 150 },
                    { field: 'specifications', title: '规格型号', width: 120 },
                    { field: 'unitsId', title: '单位', width: 80 },
                    { field: 'isEnabledDisplay', title: '状态', width: 80, templet: function(d) {
                        return d.isNo === 1 ? '<span style="color: #5FB878;">启用</span>' : '<span style="color: #FF5722;">禁用</span>';
                    }},
                    { field: 'createTimeString', title: '创建时间', width: 160 }
                ]],
                request: {
                    pageName: 'pageNumber',
                    limitName: 'pageSize'
                },
                response: {
                    statusName: 'success',
                    statusCode: true,
                    msgName: 'message',
                    countName: 'totalCount',
                    dataName: 'items'
                },
                parseData: function(res) {
                    console.log('物料产品数据响应:', res);
                    return {
                        success: res.success,
                        message: res.message,
                        totalCount: res.data ? res.data.totalCount : 0,
                        items: res.data ? res.data.items : []
                    };
                },
                done: function(res, curr, count) {
                    // 表格渲染完成后，根据已保存的物料编码勾选对应行
                    setSelectedMaterials();
                }
            });

            // 搜索物料产品
            $('#searchMaterialBtn').click(function() {
                var keyword = $('input[name="materialKeyword"]').val();
                materialTableIns.reload({
                    where: { keyword: keyword },
                    page: { curr: 1 }
                });
            });

            // 重置物料产品搜索
            $('#resetMaterialBtn').click(function() {
                $('input[name="materialKeyword"]').val('');
                materialTableIns.reload({
                    where: {},
                    page: { curr: 1 }
                });
            });

            // 新增物料（可以根据需要实现具体功能）
            $('#addMaterialBtn').click(function() {
                layer.msg('新增物料功能开发中...', {icon: 1});
            });

            // 删除选中的物料
            $('#deleteMaterialBtn').click(function() {
                var checkStatus = table.checkStatus('materialProductTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的物料', {icon: 2});
                    return;
                }
                
                layer.confirm('确定要删除选中的 ' + checkStatus.data.length + ' 项物料吗？', {icon: 3, title: '提示'}, function(index) {
                    // 这里可以根据需要实现删除逻辑
                    layer.msg('删除功能开发中...', {icon: 1});
                    layer.close(index);
                });
            });

            // 监听物料选择变化
            table.on('checkbox(materialProductTable)', function(obj) {
                collectSelectedMaterials();
            });

            // 收集选中的物料编码
            function collectSelectedMaterials() {
                var checkStatus = table.checkStatus('materialProductTable');
                var selectedCodes = checkStatus.data.map(function(item) {
                    return item.materielCode;
                });
                $('#selectedMaterielCodes').val(selectedCodes.join(','));
                console.log('选中的物料编码:', selectedCodes.join(','));
            }

            // 根据保存的物料编码设置选中状态
            function setSelectedMaterials() {
                var savedCodes = $('#selectedMaterielCodes').val();
                if (!savedCodes) return;
                
                var codeArray = savedCodes.split(',').map(function(code) {
                    return code.trim();
                }).filter(function(code) {
                    return code !== '';
                });
                
                if (codeArray.length === 0) return;
                
                console.log('准备设置选中的物料编码:', codeArray);
                
                // 等待表格数据加载完成后再设置选中状态
                setTimeout(function() {
                    // 使用jQuery选择器找到对应的复选框并勾选
                    codeArray.forEach(function(code) {
                        var $rows = $('#materialProductTable').next('.layui-table-view').find('.layui-table-body tbody tr');
                        $rows.each(function() {
                            var $row = $(this);
                            var rowData = table.cache.materialProductTable[$row.data('index')];
                            if (rowData && rowData.materielCode === code) {
                                var $checkbox = $row.find('input[type="checkbox"]');
                                if ($checkbox.length > 0) {
                                    $checkbox.prop('checked', true);
                                    $checkbox.next().addClass('layui-form-checked');
                                    rowData.LAY_CHECKED = true;
                                }
                            }
                        });
                    });
                }, 200);
            }
        });
    </script>
</body>
</html> 